//
//  HomeViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/11/25.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "HomeViewController.h"
#import "ZYBannerView.h"
#import "BookCollectionViewCell.h"
#import "MagazineCollectionViewCell.h"
#import "VideoCollectionViewCell.h"
#import "NewsTableViewCell.h"
#import "BookViewController.h"
#import "MagazineViewController.h"
#import "VideoViewController.h"
#import "CountyVideoViewController.h"
#import "NewsViewController.h"
#import "BookDetailViewController.h"
#import "MagazineDetailViewController.h"
#import "SearchViewController.h"
#import "NewsDetailViewController.h"
#import "LoginViewController.h"
#import "QRViewController.h"
#import "RegistViewController.h"
#import "CardLoginViewController.h"
#import "NewsDetailVC.h"


@interface HomeViewController () <UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, ZYBannerViewDelegate, ZYBannerViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, SearchViewDelegate, QRViewDelegate, LoginDelegate>

/** 导航条 */
@property (nonatomic, strong) UIImageView * navBar;
/** 首页主列表 */
@property (nonatomic, strong) UITableView * homeTableView;
/** 主列表头视图 */
@property (nonatomic, strong) UIView * headerView;
/** 轮播图 */
@property (nonatomic, strong) ZYBannerView * banner;
/** 轮播图数据源 */
@property (nonatomic, strong) NSArray * bannerArr;
/** 机构名称 */
@property (nonatomic, strong) UIImageView * orgNameView;
/** 热门书籍 */
@property (nonatomic, strong) UICollectionView * bookCollectionView;
/** 热门书籍数据源 */
@property (nonatomic, strong) NSArray * bookArr;
/** 推荐视频 */
@property (nonatomic, strong) UICollectionView * videoCollectionView;
/** 推荐视频数据源 */
@property (nonatomic, strong) NSArray * videoArr;
/** 县域特色-视频 */
@property (nonatomic, strong) UICollectionView * countyVideoCollectionView;
/** 视频数据源 */
@property (nonatomic, strong) NSArray * countyVideoArr;
/** 精选杂志 */
@property (nonatomic, strong) UICollectionView * magazineCollectionView;
/** 精选杂志数据源 */
@property (nonatomic, strong) NSArray * magazineArr;
/** 热点资讯 */
@property (nonatomic, strong) UITableView * newsTableView;
/** 热点资讯数据源 */
@property (nonatomic, strong) NSArray * newsArr;
/** 热门书籍布局 */
@property (nonatomic, strong) UICollectionViewFlowLayout * bookFlowLayout;
/** 杂志布局 */
@property (nonatomic, strong) UICollectionViewFlowLayout * magazineFlowLayout;
/** 推荐视频布局 */
@property (nonatomic, strong) UICollectionViewFlowLayout * videoFlowLayout;
/** 县域特色视频 */
@property (nonatomic, strong) UICollectionViewFlowLayout * countyVideoFlowLayout;
/** 视频播放器 */
@property (nonatomic, strong) MPMoviePlayerViewController * player;
/** 搜索试图控制器 */
@property (nonatomic, strong) SearchViewController * searchVC;

@end

@implementation HomeViewController

#pragma mark - lazy load

- (SearchViewController *)searchVC{
    if (!_searchVC) {
        _searchVC = [[SearchViewController alloc] init];
        _searchVC.delegate = self;
    }
    return _searchVC;
}

- (UIImageView *)orgNameView{
    if (!_orgNameView) {
        _orgNameView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(105)) / 2, self.banner.frame.size.height - HeightScale(15), WidthScale(105), HeightScale(44))];
        _orgNameView.image = ImageNamed(@"圆角矩形-4");
        _orgNameView.userInteractionEnabled = YES;
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, HeightScale(25), _orgNameView.frame.size.width, HeightScale(20))];
        nameLabel.text = [AppDelegate shareDelegate].userModel.organizationName ? [AppDelegate shareDelegate].userModel.organizationName : @"未登录";
        nameLabel.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapLogin = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loginPresent)];
        [nameLabel addGestureRecognizer:tapLogin];
        nameLabel.tag = 10;
        nameLabel.adjustsFontSizeToFitWidth = YES;
        nameLabel.textAlignment = NSTextAlignmentCenter;
        nameLabel.textColor = COLOR_FONTGRAY;
        nameLabel.font = FONTSIZE(14);
        [_orgNameView addSubview:nameLabel];
    }
    return _orgNameView;
}

- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_W / 2 + HeightScale(24))];
        [_headerView addSubview:self.banner];
        [_headerView addSubview:self.orgNameView];
        _headerView.backgroundColor = COLOR_LIGHTBGCOLOR;
    }
    return _headerView;
}

- (UIImageView *)navBar{
    if (!_navBar) {
        _navBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 64)];
        _navBar.image = ImageNamed(@"daohangtiao");
        _navBar.alpha = 0;
    }
    return _navBar;
}

- (MPMoviePlayerViewController *)player{
    if (!_player) {
        _player = [[MPMoviePlayerViewController alloc] init];
    }
    return _player;
}

- (UITableView *)newsTableView{
    if (!_newsTableView) {
        _newsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, WidthScale(44), SCREEN_W, HeightScale(330)) style:UITableViewStylePlain];
        _newsTableView.delegate = self;
        _newsTableView.dataSource = self;
        _newsTableView.bounces = NO;
        _newsTableView.tableFooterView = [UIView new];
        _newsTableView.backgroundColor = COLOR_LIGHTBGCOLOR;
        _newsTableView.showsVerticalScrollIndicator = NO;
    }
    return _newsTableView;
}

- (UICollectionView *)countyVideoCollectionView{
    if (!_countyVideoCollectionView) {
        _countyVideoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, WidthScale(44), SCREEN_W, SCREEN_W / 2 - WidthScale(44)) collectionViewLayout:self.countyVideoFlowLayout];
        _countyVideoCollectionView.delegate = self;
        _countyVideoCollectionView.dataSource = self;
        _countyVideoCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        _countyVideoCollectionView.showsHorizontalScrollIndicator = NO;
        [_countyVideoCollectionView registerClass:[VideoCollectionViewCell class] forCellWithReuseIdentifier:@"countyVideoCell"];
    }
    return _countyVideoCollectionView;
}

- (UICollectionView *)videoCollectionView{
    if (!_videoCollectionView) {
        _videoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, WidthScale(44), SCREEN_W, SCREEN_W / 2 - WidthScale(44)) collectionViewLayout:self.videoFlowLayout];
        _videoCollectionView.delegate = self;
        _videoCollectionView.dataSource = self;
        _videoCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        _videoCollectionView.showsHorizontalScrollIndicator = NO;
        [_videoCollectionView registerClass:[VideoCollectionViewCell class] forCellWithReuseIdentifier:@"videoCell"];
    }
    return _videoCollectionView;
}

- (UICollectionView *)magazineCollectionView{
    if (!_magazineCollectionView) {
        _magazineCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, WidthScale(44), SCREEN_W, SCREEN_W / 1.725 - HeightScale(44)) collectionViewLayout:self.magazineFlowLayout];
        _magazineCollectionView.delegate = self;
        _magazineCollectionView.dataSource = self;
        _magazineCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        _magazineCollectionView.showsHorizontalScrollIndicator = NO;
        [_magazineCollectionView registerClass:[MagazineCollectionViewCell class] forCellWithReuseIdentifier:@"magazineCell"];

    }
    return _magazineCollectionView;
}

- (UICollectionView *)bookCollectionView{
    if (!_bookCollectionView) {
        _bookCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, WidthScale(44), SCREEN_W, SCREEN_W / 1.725 - HeightScale(44)) collectionViewLayout:self.bookFlowLayout];
        _bookCollectionView.delegate = self;
        _bookCollectionView.dataSource = self;
        _bookCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        _bookCollectionView.showsHorizontalScrollIndicator = NO;
        [_bookCollectionView registerClass:[BookCollectionViewCell class] forCellWithReuseIdentifier:@"bookCell"];

    }
    return _bookCollectionView;
}

- (UICollectionViewFlowLayout *)countyVideoFlowLayout{
    if (!_countyVideoFlowLayout) {
        _countyVideoFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _countyVideoFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _countyVideoFlowLayout;
}

- (UICollectionViewFlowLayout *)videoFlowLayout{
    if (!_videoFlowLayout) {
        _videoFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _videoFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _videoFlowLayout;
}

- (UICollectionViewFlowLayout *)magazineFlowLayout{
    if (!_magazineFlowLayout) {
        _magazineFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _magazineFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _magazineFlowLayout;
}

- (UICollectionViewFlowLayout *)bookFlowLayout{
    if (!_bookFlowLayout) {
        _bookFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _bookFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _bookFlowLayout;
}

- (ZYBannerView *)banner{
    if (!_banner) {
        _banner = [[ZYBannerView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_W / 2)];
        _banner.backgroundColor = COLOR_LIGHTBGCOLOR;
        _banner.dataSource = self;
        _banner.delegate = self;
        _banner.shouldLoop = YES;//允许循环滚动
        _banner.autoScroll = YES;//允许自动滚动
        _banner.scrollInterval = 3.0;//自动滚动间隔
        _banner.pageControl.hidden = YES;
    }
    return _banner;
}

- (UITableView *)homeTableView{
    if (!_homeTableView) {
        _homeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H - self.tabBarController.tabBar.height) style:UITableViewStyleGrouped];
        _homeTableView.delegate = self;
        _homeTableView.dataSource = self;
        _homeTableView.bounces = YES;
        _homeTableView.showsVerticalScrollIndicator = NO;
        _homeTableView.backgroundColor = COLOR_DEEPBGCOLOR;
        _homeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _homeTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestAll)];
        
        if (@available(iOS 11.0, *)) {
            _homeTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
        
    }
    return _homeTableView;
}

#pragma mark - lify cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_DEEPBGCOLOR;
    self.automaticallyAdjustsScrollViewInsets = NO;

    //设置搜索按钮
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[ImageNamed(@"search") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(searchButtonClicked:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    //设置扫描按钮
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[ImageNamed(@"扫一扫-2") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(QRButtonClicked:)];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    [self.view addSubview:self.homeTableView];
    
    [self.view addSubview:self.navBar];
    
    [self requestBanner];
    
    [self requestCountyNews];
    
    [self requestCountyVideo];
    
    [self requestVideo];
    
    [self requestMagazine];
    
    [self requestBook];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestAll) name:@"loginSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestAll) name:@"logoutSuccess" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //轮播图开始滚动
    [self.banner startTimer];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //轮播图停止滚动
    [self.banner stopTimer];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.1 animations:^{
        [AppDelegate shareDelegate].tabBar.customBar.center = CGPointMake(SCREEN_W / 2, SCREEN_H - [AppDelegate shareDelegate].tabBar.customBar.frame.size.height / 2);
    }];
    
    [Tool setNavigationBarType:self];
    
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
}

#pragma mark - MPMoviePlayerPlaybackDidFinishNotification Method

- (void)videoFinished{
    DLog(@"停止播放");
    if (self.player) {
        self.player = nil;
    }
}

- (void)noMoreVideos{
    
    for (UIView *subView in self.player.view.subviews) {
        DLog(@"%@", subView);
        for (UIView *subview in subView.subviews) {
            DLog(@"subView %@", subview);
            for (UIView *subView2 in subview.subviews) {
                for (UIView *subview3 in subView2.subviews) {
                    for (UIView *subview4 in subview3.subviews) {
                        for (UIView *subview5 in subview4.subviews) {
                            if ([subview5 isKindOfClass:[UIButton class]]) {
                                DLog(@"%@", subview5);
                                if (subview5.frame.size.width == 32) {
                                    UIButton *button = (UIButton *)subview5;
                                    [button removeTarget:nil
                                                  action:NULL
                                        forControlEvents:UIControlEventAllEvents];
                                    [button initWithBlock:^(id obj) {
                                        [ZRProgressHUD showMsgWithoutView:@"没有更多了"];
                                    } for:UIControlEventTouchUpInside];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

- (void)dealloc{
    
    DLog(@"%s", __func__);
}

#pragma mark - UITableViewDataSource & UITableViewDelegate Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([tableView isEqual:self.homeTableView]) {
        return 5;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.homeTableView]) {
        return 1;
    } else if ([tableView isEqual:self.newsTableView]){
        return (self.newsArr.count >= 3) ? 3 : self.newsArr.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.homeTableView] && indexPath.section == 0) {
        //热门书籍
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, HeightScale(15), WidthScale(3.5), HeightScale(14))];
        imageView.image = ImageNamed(@"矩形-75-拷贝-2");
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + WidthScale(15), 0, WidthScale(100), HeightScale(44))];
        titleLabel.text = @"热门书籍";
        titleLabel.font = FONTSIZE(17);
        titleLabel.textColor = COLOR_FONTBLACK;
        
        UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(54), 0, WidthScale(44), HeightScale(44))];
        [moreButton setImage:ImageNamed(@"more") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [moreButton initWithBlock:^(id obj) {
            DLog(@"热门书籍更多");
            BookViewController *bookVC = [[BookViewController alloc] init];
            bookVC.title = @"热门书籍";
            [weakSelf.navigationController pushViewController:bookVC animated:YES];
            
        } for:UIControlEventTouchUpInside];
        
        [cell.contentView addSubview:moreButton];
        
        [cell.contentView addSubview:titleLabel];
        
        [cell.contentView addSubview:imageView];
        
        [cell.contentView addSubview:self.bookCollectionView];
        
        cell.contentView.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    } else if ([tableView isEqual:self.homeTableView] && indexPath.section == 1) {
        //精选杂志
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, HeightScale(15), WidthScale(3.5), HeightScale(14))];
        imageView.image = ImageNamed(@"矩形-75-拷贝-2");
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + WidthScale(15), 0, WidthScale(100), HeightScale(44))];
        titleLabel.text = @"精选杂志";
        titleLabel.font = FONTSIZE(17);
        titleLabel.textColor = COLOR_FONTBLACK;
        
        UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(54), 0, WidthScale(44), HeightScale(44))];
        [moreButton setImage:ImageNamed(@"more") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [moreButton initWithBlock:^(id obj) {
            DLog(@"精选杂志更多");
            MagazineViewController *magazineVC = [[MagazineViewController alloc] init];
            [weakSelf.navigationController pushViewController:magazineVC animated:YES];
        } for:UIControlEventTouchUpInside];
        
        [cell.contentView addSubview:moreButton];
        
        [cell.contentView addSubview:titleLabel];
        
        [cell.contentView addSubview:imageView];
        
        [cell.contentView addSubview:self.magazineCollectionView];
        
        cell.contentView.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    } else if ([tableView isEqual:self.homeTableView] && indexPath.section == 2) {
        //推荐视频
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, HeightScale(15), WidthScale(3.5), HeightScale(14))];
        imageView.image = ImageNamed(@"矩形-75-拷贝-2");
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + WidthScale(15), 0, WidthScale(100), HeightScale(44))];
        titleLabel.text = @"推荐视频";
        titleLabel.font = FONTSIZE(17);
        titleLabel.textColor = COLOR_FONTBLACK;
        
        UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(54), 0, WidthScale(44), HeightScale(44))];
        [moreButton setImage:ImageNamed(@"more") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [moreButton initWithBlock:^(id obj) {
            DLog(@"推荐视频更多");
            VideoViewController *videoVC = [[VideoViewController alloc] init];
            videoVC.title = @"推荐视频";
            [weakSelf.navigationController pushViewController:videoVC animated:YES];
       } for:UIControlEventTouchUpInside];

        [cell.contentView addSubview:moreButton];
        
        [cell.contentView addSubview:titleLabel];
        
        [cell.contentView addSubview:imageView];
        
        [cell.contentView addSubview:self.videoCollectionView];
        
        cell.contentView.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    } else if ([tableView isEqual:self.homeTableView] && indexPath.section == 3) {
        //热点资讯
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, HeightScale(15), WidthScale(3.5), HeightScale(14))];
        imageView.image = ImageNamed(@"矩形-75-拷贝-2");
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + WidthScale(15), 0, WidthScale(100), HeightScale(44))];
        titleLabel.text = @"热点资讯";
        titleLabel.font = FONTSIZE(17);
        titleLabel.textColor = COLOR_FONTBLACK;
        
        UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(54), 0, WidthScale(44), HeightScale(44))];
        [moreButton setImage:ImageNamed(@"more") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [moreButton initWithBlock:^(id obj) {
            DLog(@"热点资讯更多");
            NewsViewController *newsVC = [[NewsViewController alloc] init];
            newsVC.title = @"热点资讯";
            [weakSelf.navigationController pushViewController:newsVC animated:YES];
            
        } for:UIControlEventTouchUpInside];

        [cell.contentView addSubview:moreButton];
        
        [cell.contentView addSubview:titleLabel];
        
        [cell.contentView addSubview:imageView];
        
        [cell.contentView addSubview:self.newsTableView];
        
        cell.contentView.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    
    } else if ([tableView isEqual:self.homeTableView] && indexPath.section == 4) {
        //县域特色
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, HeightScale(15), WidthScale(3.5), HeightScale(14))];
        imageView.image = ImageNamed(@"矩形-75-拷贝-2");
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + WidthScale(15), 0, WidthScale(100), HeightScale(44))];
        titleLabel.text = @"县域特色";
        titleLabel.font = FONTSIZE(17);
        titleLabel.textColor = COLOR_FONTBLACK;
        
        UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(54), 0, WidthScale(44), HeightScale(44))];
        [moreButton setImage:ImageNamed(@"more") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [moreButton initWithBlock:^(id obj) {
            DLog(@"县域特色更多");
            CountyVideoViewController *countyVideoVC = [[CountyVideoViewController alloc] init];
            countyVideoVC.title = @"县域特色";
            [weakSelf.navigationController pushViewController:countyVideoVC animated:YES];
        } for:UIControlEventTouchUpInside];

        [cell.contentView addSubview:moreButton];
        
        [cell.contentView addSubview:titleLabel];
        
        [cell.contentView addSubview:imageView];
        
        [cell.contentView addSubview:self.countyVideoCollectionView];
        
        cell.contentView.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
        
    } else {
        static NSString *cellID = @"newsCell";
        NewsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }

        cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.newsArr[indexPath.row][@"title"]];

        cell.timeLabel.text = [NSString stringWithFormat:@"%@", self.newsArr[indexPath.row][@"publishTime"]];
        
        NSString *imagePath = [NSString stringWithFormat:@"%@%@", KHostAddress, self.newsArr[indexPath.row][@"imagePath"]];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:nil];

        
        if (indexPath.row == 2) {
            cell.underLine.hidden = YES;
        }
        return cell;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.newsTableView]) {
        DLog(@"index = %ld", indexPath.row);
        //新闻
    
        NewsDetailVC *newsDetailVC = [[NewsDetailVC alloc] init];
        newsDetailVC.dataDic = self.newsArr[indexPath.row];
        newsDetailVC.title = @"热点资讯";
        [self.navigationController pushViewController:newsDetailVC animated:YES];
        
//        NewsDetailViewController *newsVC = [[NewsDetailViewController alloc] init];
//        newsVC.title = @"热点资讯";
//        newsVC.dataDic = self.newsArr[indexPath.row];
//        [self.navigationController pushViewController:newsVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.homeTableView]) {
        if (indexPath.section == 0 || indexPath.section == 1) {
            return SCREEN_W / 1.725;
        } else if (indexPath.section == 2 || indexPath.section == 4) {
            return SCREEN_W / 2;
        } else if (indexPath.section == 3){
            return SCREEN_W * 0.905;
        } else {
            return CGFLOAT_MIN;
        }
    } else if ([tableView isEqual:self.newsTableView]) {
        return HeightScale(104);
    } else {
        return CGFLOAT_MIN;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:self.homeTableView] && section == 0) {
        //头视图(轮播图)
        return SCREEN_W / 2 + HeightScale(24);
    } else if ([tableView isEqual:self.newsTableView]) {
        return CGFLOAT_MIN;
    } else {
        return 5;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if ([tableView isEqual:self.homeTableView]) {
        return 5;
    } else {
        return CGFLOAT_MIN;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:self.homeTableView] && section == 0) {
        return self.headerView;
    } else {
        return [[UIView alloc] init];
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UICollectionViewDelegate & UICollectionViewDataSource Methods

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([collectionView isEqual:self.countyVideoCollectionView]) {
        return self.countyVideoArr.count;
    } else if ([collectionView isEqual:self.magazineCollectionView]){
        return self.magazineArr.count;
    } else if ([collectionView isEqual:self.bookCollectionView]){
        return self.bookArr.count;
    } else {
        return self.videoArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([collectionView isEqual:self.bookCollectionView]) {
        BookCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"bookCell" forIndexPath:indexPath];
        
        cell.authorLabel.text = [NSString stringWithFormat:@"%@", self.bookArr[indexPath.row][@"author"]];
        cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.bookArr[indexPath.row][@"name"]];
        
        NSString *coverImageFile = [NSString stringWithFormat:@"%@%@", KHostAddress, self.bookArr[indexPath.row][@"coverImageFile"]];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverImageFile] placeholderImage:ImageNamed(@"placeholdershuji")];

        return cell;
    } else if ([collectionView isEqual:self.magazineCollectionView]) {
        MagazineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"magazineCell" forIndexPath:indexPath];
        
        cell.authorLabel.text = @"";
        cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.magazineArr[indexPath.row][@"name"]];
        
        NSString *coverimgpath = [NSString stringWithFormat:@"%@%@", KHostAddress, self.magazineArr[indexPath.row][@"coverimgpath"]];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverimgpath] placeholderImage:ImageNamed(@"placeholdershuji")];

        
        return cell;
    } else if ([collectionView isEqual:self.videoCollectionView]) {
        VideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"videoCell" forIndexPath:indexPath];
        
        cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.videoArr[indexPath.row][@"name"]];
        
        NSString *coverimagefile = [NSString stringWithFormat:@"%@%@", KHostAddress, self.videoArr[indexPath.row][@"coverImageFile"]];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverimagefile] placeholderImage:ImageNamed(@"placeholdershipin")];

        
        return cell;
    } else {
        VideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"countyVideoCell" forIndexPath:indexPath];
        
        cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.countyVideoArr[indexPath.row][@"name"]];
        NSString *coverimagefile = [NSString stringWithFormat:@"%@%@", KHostAddress, self.countyVideoArr[indexPath.row][@"coverimagefile"]];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverimagefile] placeholderImage:ImageNamed(@"placeholdershipin")];

        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    DLog(@"index = %ld", indexPath.row);
    
    if ([collectionView isEqual:self.bookCollectionView]) {
        BookDetailViewController *bookDetailVC = [[BookDetailViewController alloc] init];
        bookDetailVC.bookDic = self.bookArr[indexPath.row];
        [self.navigationController pushViewController:bookDetailVC animated:YES];
    } else if ([collectionView isEqual:self.magazineCollectionView]) {
        MagazineDetailViewController *magazineDetailVC = [[MagazineDetailViewController alloc] init];
        magazineDetailVC.magazineDic = self.magazineArr[indexPath.row];
        [self.navigationController pushViewController:magazineDetailVC animated:YES];
    } else if ([collectionView isEqual:self.videoCollectionView]) {
        DLog(@"播放视频");
        if ([self.videoArr[indexPath.row][@"filePath"] isKindOfClass:[NSNull class]]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"视频地址不存在" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        } else {
            NSString *url = [NSString stringWithFormat:@"%@%@", KHostAddress, self.videoArr[indexPath.row][@"filePath"]];
            self.player.moviePlayer.contentURL = [NSURL URLWithString:url];
            [self presentViewController:self.player animated:YES completion:^{
                [self requestHistory:indexPath ID:self.videoArr[indexPath.row][@"did"]];
                [self requestStatistics:indexPath ID:self.videoArr[indexPath.row][@"id"] type:@"2"];
                [self requestAddShelfOfVideo:self.videoArr[indexPath.row][@"id"]];
                [self noMoreVideos];
            }];
        }
    } else if ([collectionView isEqual:self.countyVideoCollectionView]) {
        if ([self.countyVideoArr[indexPath.row][@"filepath"] isKindOfClass:[NSNull class]]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"视频地址不存在" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        } else if (self.countyVideoArr[indexPath.row][@"filepath"] == nil) {
            NewsDetailVC *newsDetailVC = [[NewsDetailVC alloc] init];
            newsDetailVC.dataDic = self.countyVideoArr[indexPath.row];
            [self.navigationController pushViewController:newsDetailVC animated:YES];
//            NewsDetailViewController *newsDetailVC = [[NewsDetailViewController alloc] init];
//            newsDetailVC.dataDic = self.countyVideoArr[indexPath.row];
//            [self.navigationController pushViewController:newsDetailVC animated:YES];
        }
        
        else {
            NSString *url = [NSString stringWithFormat:@"%@%@", KHostAddress, self.countyVideoArr[indexPath.row][@"filepath"]];
            self.player.moviePlayer.contentURL = [NSURL URLWithString:url];
            [self presentViewController:self.player animated:YES completion:^{
//                [self requestHistory:indexPath ID:self.countyVideoArr[indexPath.row][@"did"]];
                [self requestStatistics:indexPath ID:self.videoArr[indexPath.row][@"id"] type:@"5"];
                //县域视频不用记录浏览历史
                [self noMoreVideos];
            }];
        }
    } else {
        
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([collectionView isEqual:self.bookCollectionView] || [collectionView isEqual:self.magazineCollectionView]) {
        return CGSizeMake(WidthScale(collectionView.frame.size.height / 2), HeightScale(collectionView.frame.size.height));
    } else if ([collectionView isEqual:self.videoCollectionView] || [collectionView isEqual:self.countyVideoCollectionView]) {
        return CGSizeMake(SCREEN_W / 2 - WidthScale(20), (SCREEN_W / 2 - WidthScale(20)) / 3 * 2);
    } else {
        return CGSizeMake(0, 0);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if ([collectionView isEqual:self.bookCollectionView] || [collectionView isEqual:self.magazineCollectionView]) {
        return UIEdgeInsetsMake(0, WidthScale(28), 0, WidthScale(28));
    } else {
        return UIEdgeInsetsMake(0, WidthScale(10), WidthScale(25), WidthScale(10));
    }
    
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if ([collectionView isEqual:self.bookCollectionView] || [collectionView isEqual:self.magazineCollectionView]) {
        return WidthScale(20);
    } else if ([collectionView isEqual:self.videoCollectionView] || [collectionView isEqual:self.countyVideoCollectionView]) {
        return WidthScale(10);
    }
    return 0;
}

#pragma mark - UIScrollViewDelegate Method

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isEqual:self.homeTableView]) {
        self.navBar.alpha = scrollView.contentOffset.y / (SCREEN_W / 2 - 64);
    }
}

#pragma mark - ZYBannerViewDelegate & ZYBannberDataSource Methods

- (NSInteger)numberOfItemsInBanner:(ZYBannerView *)banner{
    return self.bannerArr.count;
}

- (UIView *)banner:(ZYBannerView *)banner viewForItemAtIndex:(NSInteger)index{
    UIImageView *imageView = [[UIImageView alloc] init];
    NSString *imagePath = self.bannerArr[index][@"imagePath"];
    [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, imagePath]] placeholderImage:ImageNamed(@"placeholderBanner")];
    return imageView;
}

- (void)banner:(ZYBannerView *)banner didSelectItemAtIndex:(NSInteger)index{
    DLog(@"轮播图 index = %ld", index);
    
}

#pragma mark - 点击事件

- (void)loginPresent{
    UILabel *label = (UILabel *)[self.orgNameView viewWithTag:10];
    if ([label.text isEqualToString:@"未登录"]) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        loginVC.delegate = self;
        [self presentViewController:loginVC animated:YES completion:nil];
    } else {
        DLog(@"已登录");
    }
    
}

- (void)registPresent{
    RegistViewController *registVC = [[RegistViewController alloc] init];
    [self presentViewController:registVC animated:YES completion:nil];
}

- (void)QRButtonClicked:(UIBarButtonItem *)barButtonItem{
    QRViewController *qrVC = [[QRViewController alloc] init];
    qrVC.delegate = self;
    [self.navigationController pushViewController:qrVC animated:YES];
}

- (void)searchButtonClicked:(UIBarButtonItem *)barButtonItem{
    DLog(@"搜索");
    [self presentViewController:self.searchVC animated:NO completion:nil];
}

- (void)resultDetail:(NSInteger)type dataDic:(NSDictionary *)dic{
    if (type == 1) {//书籍
        BookDetailViewController *bookDetailVC = [[BookDetailViewController alloc] init];
        bookDetailVC.bookDic = dic;
        [self.navigationController pushViewController:bookDetailVC animated:YES];
    } else if (type == 4) {//期刊
        MagazineDetailViewController *magazineDetailVC = [[MagazineDetailViewController alloc] init];
        magazineDetailVC.magazineDic = dic;
        [self.navigationController pushViewController:magazineDetailVC animated:YES];
    } else {
        
        if ([dic[@"filePath"] isKindOfClass:[NSNull class]]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"视频地址不存在" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        } else {
            NSString *url = [NSString stringWithFormat:@"%@%@", KHostAddress, dic[@"filePath"]];
            self.player.moviePlayer.contentURL = [NSURL URLWithString:url];
            [self presentViewController:self.player animated:YES completion:^{
                [self requestHistory:nil ID:dic[@"did"]];
            }];
        }
    }
}

- (void)sacnCard:(NSDictionary *)dic cardNumber:(NSString *)u cardPwd:(NSString *)rcpwd{
    if ([[dic objectForKey:@"data"][@"mobileNumber"] length] != 11) {
        DLog(@"没有注册");
        RegistViewController *registVC = [[RegistViewController alloc] init];
        registVC.cardNumber = u;
        registVC.location = dic[@"data"][@"organizationName"];
        registVC.cardPwd = rcpwd;
        [self presentViewController:registVC animated:YES completion:nil];
    } else {
        //已注册，去登录
        CardLoginViewController *cardLoginVC = [[CardLoginViewController alloc] init];
        cardLoginVC.phoneNumber = dic[@"data"][@"mobileNumber"];
        cardLoginVC.cardNumber = u;
        cardLoginVC.cardPwd = rcpwd;
        [self presentViewController:cardLoginVC animated:YES completion:nil];
    }
}

#pragma mark - data request

/** 轮播图 */
- (void)requestBanner{
    NSString *URL = [NSString stringWithFormat:KBannerURL, KHostAddress];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            self.bannerArr = [NSArray arrayWithArray:[[responseObject objectForKey:@"data"] objectForKey:@"items"]];
            [self.banner reloadData];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 县域特色 - 新闻资讯 */
- (void)requestCountyNews{
    NSString *URL = [NSString stringWithFormat:KNEWSURL, KHostAddress, @(1), KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            self.newsArr = [NSArray arrayWithArray:responseObject[@"data"][@"items"]];
            [self.newsTableView reloadData];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 县域 - 视频 */
- (void)requestCountyVideo{
    NSString *URL = [NSString stringWithFormat:KCountyVideo, KHostAddress, @(1), KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            self.countyVideoArr = [NSArray arrayWithArray:responseObject[@"data"][@"items"]];
            [self.countyVideoCollectionView reloadData];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 推荐视频 */
- (void)requestVideo{
    NSString *URL = [NSString stringWithFormat:KgetVideoByClick, KHostAddress, KOrganizationID, @(1), @"", @"", @(1)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            self.videoArr = [NSArray arrayWithArray:responseObject[@"data"][@"items"]];
            [self.videoCollectionView reloadData];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 精选杂志（期刊） */
- (void)requestMagazine{
    NSString *URL = [NSString stringWithFormat:KMagazine, KHostAddress, KOrganizationID, @(1)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            self.magazineArr = [NSArray arrayWithArray:responseObject[@"data"][@"items"]];
            [self.magazineCollectionView reloadData];
        } else {
            self.magazineArr = [NSArray array];
            [self.magazineCollectionView reloadData];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 热门书籍 */
- (void)requestBook{
    DLog(@"%@", [AppDelegate shareDelegate].userModel.organizationId);
    NSString *URL = [NSString stringWithFormat:KBook, KHostAddress, KOrganizationID, @(1)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            self.bookArr = [NSArray arrayWithArray:responseObject[@"data"][@"items"]];
            [self.bookCollectionView reloadData];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 添加浏览历史(视频) */
- (void)requestHistory:(NSIndexPath *)indexPath ID:(NSString *)ID{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        NSString *URL = [NSString stringWithFormat:KaddHistory, KHostAddress, ID, @(2), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            DLog(@"添加浏览历史");
        } failure:^(NSError *error) {
            DLog(@"添加浏览历史失败");
        }];
    }
}

/** 添加统计 */
- (void)requestStatistics:(NSIndexPath *)indexPath ID:(NSString *)ID type:(NSString *)type{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        //1、图书；2、视频；3、音频；4、期刊杂志5、县域视频6、资讯
        NSString *URL = [NSString stringWithFormat:Kstatistics, KHostAddress, KCurrentIP, [AppDelegate shareDelegate].userModel.userId, KOrganizationID, type, ID];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加统计成功");
            } else {
                DLog(@"添加统计失败");
            }
        } failure:^(NSError *error) {
            DLog(@"%@", error);
        }];
    }
}

/** 视频添加到书架 */
- (void)requestAddShelfOfVideo:(NSString *)ID{
    if ([AppDelegate shareDelegate].userModel) {
        NSString *URL = [NSString stringWithFormat:KaddShelf, KHostAddress, ID, @(2), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加书架成功");
            } else {
                DLog(@"添加书架失败");
            }
            
            
        } failure:^(NSError *error) {
            DLog(@"添加书架失败");
        }];
    }
}

- (void)requestAll{
    [self requestBanner];
    [self requestBook];
    [self requestVideo];
    [self requestMagazine];
    [self requestCountyNews];
    [self requestCountyVideo];
    
    UILabel *label = (UILabel *)[self.orgNameView viewWithTag:10];
    label.text = [AppDelegate shareDelegate].userModel.organizationName ? [AppDelegate shareDelegate].userModel.organizationName : @"未登录";
    
    [self.homeTableView.mj_header endRefreshing];
}

@end
